package com.ruicar.afs.cloud.bizcommon.print.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormClass;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormManage;
import com.ruicar.afs.cloud.bizcommon.print.mapper.ComPrintFormClassMapper;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormClassService;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormManageService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * 打印模板类别管理
 *
 * @author phong
 * @version 1.0
 * @created 2020/6/8 11:40
 */
@Service
@AllArgsConstructor
@Slf4j
public class ComPrintFormClassServiceImpl extends ServiceImpl<ComPrintFormClassMapper, ComPrintFormClass> implements ComPrintFormClassService {

    private ComPrintFormManageService comPrintFormManageService;

    public Boolean saveTemplateClass(ComPrintFormClass dto) {
        testKey(dto);
        // 数据保存
        this.baseMapper.insert(dto);
        return Boolean.TRUE;
    }

    /**
     * 删除类别
     * 说明:类别下有模板则不允许删除
     *
     * @param classNo 模板编号
     */
    @Override
    public Boolean delTemplateClass(String classNo) {
        Assert.isTrue(StrUtil.isNotBlank(classNo), "未选中需要删除的模板类别");
        // 通过类别查询
        List<ComPrintFormManage> templates = comPrintFormManageService.list((Wrappers.<ComPrintFormManage>lambdaQuery()
                .eq(ComPrintFormManage::getClassNo, classNo)));
        Assert.isTrue(CollUtil.isEmpty(templates), "当前类别下已有模板，不允许从删除");

        this.baseMapper.delete(Wrappers.<ComPrintFormClass>lambdaQuery().eq(ComPrintFormClass::getClassId, classNo));

        return Boolean.TRUE;
    }

    @Override
    public Boolean modifyTemplateClass(ComPrintFormClass dto) {
        this.baseMapper.updateById(dto);
        return Boolean.TRUE;
    }

    private void testKey(ComPrintFormClass dto) {
        long count = this.baseMapper.selectCount(Wrappers.<ComPrintFormClass>lambdaQuery()
                .eq(ComPrintFormClass::getClassId, dto.getClassId()));
        Assert.isTrue(count < 1, "编号[" + dto.getClassId() + "]重复");
    }

}
